#include "front/front_interface.h"
using namespace std;
using namespace ppspeech;


//加载字典映射表
bool FrontEngineInterface::FrontSetDictMap(const string& fInDictFilePath, const string fInSplitSymbol, map<string, string>* fOutDictMap)
{
	if(fOutDictMap != NULL) {
		fOutDictMap->clear();
	}

	ifstream tFileIfstream(fInDictFilePath.c_str(), ifstream::in);
	if (!tFileIfstream.good()) {
		printf("ERROR: Frontend: Cannot open dict file: %s\n", fInDictFilePath.c_str());
		return false;
	}
	string line, key, value;
	while (getline(tFileIfstream, line)) {
		size_t pos = line.find_first_of(fInSplitSymbol, 0);
		key = line.substr(0, pos);
		value = line.substr(pos + 1);
		(*fOutDictMap)[key] = value;
	}
	tFileIfstream.close();
	return true;
}


//加载字典映射表
bool FrontEngineInterface::FrontPinyinMap(const string& fInDictFilePath, map<string, pair<string,string> >* fOutDictMap)
{
	if(fOutDictMap != NULL) {
		fOutDictMap->clear();
	}

	ifstream tFileIfstream(fInDictFilePath.c_str(), ifstream::in);
	if (!tFileIfstream.good()) {
		printf("ERROR: Frontend: Cannot open dict file: %s\n", fInDictFilePath.c_str());
		return false;
	}
	string line;
	while (getline(tFileIfstream, line)) {
		const vector<string> tcvSplitTab = StrSplit(line, "\t");
		if(tcvSplitTab.size() != 2) {
			continue;
		}
		const vector<string> tcvSplitSpace = StrSplit(tcvSplitTab[1], " ");
		if(tcvSplitSpace.size() != 2) {
			continue;
		}

		(*fOutDictMap)[ tcvSplitTab[0] ] = pair<string,string>(tcvSplitSpace[0], tcvSplitSpace[1]);
	}
	tFileIfstream.close();
	return true;
}



//utf8字符串切分出每个字
//1byte: 0xxx xxxx
//2byte: 110x xxxx  10xx xxxx
//3byte: 1110 xxxx  10xx xxxx  10xx xxxx
//4byte: 1111 0xxx  10xx xxxx  10xx xxxx  10xx xxxx
vector<string> FrontEngineInterface::FrontUtf8WordSplit(const string& fInputStr)
{
	vector<string> tSplitWords;
	const char* cstr = fInputStr.c_str();
	for(size_t i=0; i<fInputStr.length(); i++) {
		const unsigned char c = cstr[i];
		if((c & 0xF8) == 0xF0) {
			tSplitWords.push_back( fInputStr.substr(i, 4) );
			i+=3;
		}
		else if((c & 0xF0) == 0xE0) {
			tSplitWords.push_back( fInputStr.substr(i, 3) );
			i+=2;
		}
		else if((c & 0xE0) == 0xC0) {
			tSplitWords.push_back( fInputStr.substr(i, 2) );
			i+=1;
		}
		else {
			tSplitWords.push_back( fInputStr.substr(i, 1) );
		}
	}
	return tSplitWords;
}


//繁体字转简体字
int FrontEngineInterface::TraditionalToSimplified(const wstring &sentence, wstring *sentence_simp)
{
	// sentence_simp = sentence;
	for (int i = 0; i < sentence.length(); i++) {
		wstring temp(1, sentence[i]);
		string sigle_word = ppspeech::wstring2utf8string(temp);
		// 单个字是否在繁转简的字典里
		string t = mDictionary.find_sqlite_dict(DatabaseDictTableZhTrand, sigle_word);
		if (t == "") {
			sentence_simp->append(temp);
		}
		else {
			sentence_simp->append( (ppspeech::utf8string2wstring(t)) );
		}
	}

	return 0;
}